import React from 'react';
import { Button, Form, Input,notification } from 'antd';
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';
import service from '../../api'
import './Login.scss'
function Login(props) {
    var dispatch = useDispatch()
    var navigate = useNavigate();
    //表单验证通过时执行
    const onFinish = async (values) => {
        //发出登陆请求
        var res = await service.admin.admin_login( values )
        //保证页面只有一个通知，下个通知出现前 销毁上一个
        notification.destroy();
        if( res.data.code == 200 ){
            //弹出通知框
            notification.success({message:'登陆成功!'});
            //保存用户信息到store中
            dispatch({ type:'SAVE_USERINFO',payload: res.data.data })
            //跳转到首页
            navigate('/index');
        }else{
            notification.error({message:'登陆失败!'});
        }
    };
    //验证手机号
    var adminnameValidator = (rule, value, callback) => {
        if ( value.length<7) {
            callback()
        } else {
            callback(new Error('账户格式错误，请重新输入!'))
        }
    }
    //验证密码
    var passwordValidator = (rule, value, callback) => {
        if (/^\d{6}$/.test(value)) {
            callback()
        } else {
            callback(new Error('密码格式错误，请重新输入'))
        }
    }
    return (
        <div className='login-box'>

            <h3>嗨购后台管理系统</h3>

            <Form
                className="login-form"
                style={{ maxWidth: 600 }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item name="adminname" rules={[{ validator: adminnameValidator }]}>
                    <Input />
                </Form.Item>

                <Form.Item name="password" rules={[{ validator: passwordValidator }]}>
                    <Input.Password />
                </Form.Item>


                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        登陆
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Login;